package org.example.Servlet.vote;

import org.example.Dao.TopicDao;
import org.example.Dao.VoteDao;
import org.example.entity.Person;
import org.example.entity.TopAndOpt;
import org.example.entity.VoteResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/vote/show")
public class ShowVoteServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int tid = Integer.parseInt(req.getParameter("tid"));
        VoteResult voteResult = new VoteResult();
        HttpSession session = req.getSession();
        TopicDao topicDao = new TopicDao();
        VoteDao voteDao = new VoteDao();
        try {
            // 先获取该条主题的信息
            TopAndOpt topicAndOption = topicDao.getTopicAndOption(tid);
            voteResult.setTopAndOpt(topicAndOption);
            // 获取该主题的投票结果
            int count = voteDao.getVoteCount(tid);
            System.out.println("vote count ==> " + count);
            voteResult.setCount(count);
            //判断当前用户是否透过票
            Person person = (Person) session.getAttribute("person");
            count = voteDao.isVoted(person.getPid(), tid);
            System.out.println("person is voted ==> " + count);
            voteResult.setIsVote(count);
            System.out.println("vote voteResult ==> " + voteResult.toString());
            session.setAttribute("voteResult", voteResult);
            resp.sendRedirect(req.getContextPath() + "/views/topic/vote.jsp");
        } catch (Exception e) {
            System.out.println("show vote error ==> " + e.getMessage());
            req.getRequestDispatcher("/views/user/index").forward(req, resp);
        }
    }
}
